package com.itheima.reggie.filter;


import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@WebFilter(filterName = "LoginCheckFilter",urlPatterns = "/*")
public class LoginCheckFilter implements Filter {

    //路径匹配器用于匹配路径
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        //先将servletRequest请求和servletResponse响应类型强转成httpServlet类型
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //获取请求的url
        String url = request.getRequestURI();
        log.info("请求的url:{}",url);

        //定义不需要拦截的请求路径
        String[] urls = {
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**"
        };

        //判断本次请求是否需要处理
        boolean check = check(url, urls);

        //如果不需要处理，则直接放行
        if (check){
            filterChain.doFilter(request,response);//放行
            return;
        }

        //判断登录状态，如果已经登录，则直接放行
        if (request.getSession().getAttribute("employee") != null){

            //登录时获取登录人id
            Long empId = (Long) request.getSession().getAttribute("employee");

            //直接在BaseContext中存储id为了以后方便使用
            BaseContext.setCurrentId(empId);

            filterChain.doFilter(request,response);//放行
            return;

        }

        //如果未登录则返回未登录结果，通过输出流方式向客户端响应数据
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;


/*        //判断请求url中是否包含login，如果包含说明是登录操作放行


        //如果不是登录请求，先获取请求头中的令牌(token)
        //获取请求头中的令牌(token)
        String jwt = request.getHeader("token");

        //4.判断令牌是否存在，如果不存在，返回错误结果(未登录)
        if (!StringUtils.hasLength(jwt)){
            response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));

            return;
        }

        //5.如果存在jwt令牌，则解析token，如果解析失败，返回错误结果(未登录)
        try {
            JwtUtils.parseJWT(jwt);//解析jwt令牌
        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));

            return;
        }


        //6.放行
        log.info("令牌合法，放行");
        filterChain.doFilter(request,response);*/


    }

    /*
    * 判断请求的url中是否包含不需要拦截的请求路径
    *
    * */
    public boolean check(String url, String[] urls){
        for (String someUrl : urls) {
            boolean match = PATH_MATCHER.match(someUrl, url);//匹配路径
            if (match){
                return true;
            }
        }
        return false;

    }


}
